package com.zb.test;
import com.zb.Interface.MyThreadLocal;
import org.junit.Test;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class JAVA8_12_SimpleDateFormat出现的线程安全问题 {
    @Test
    public void test1() throws ExecutionException, InterruptedException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Callable<Date> task = new Callable<Date>() {
            @Override
            public Date call() throws Exception {
                return sdf.parse("2018-04-05");
            }
        };

        ExecutorService pool = Executors.newFixedThreadPool(10);//创建一个线程池
        List<Future<Date>> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Future<Date> res = pool.submit(task);
            list.add(res);
        }
        pool.shutdown();
        System.out.println(list.size());
        for (Future<Date> f : list) {
            System.out.println(f.get());
        }
    }

    //采用ThreadLocal解决上述问题
    @Test
    public void test2() throws ExecutionException, InterruptedException {
        Callable<Date> task = new Callable<Date>() {
            @Override
            public Date call() throws Exception {
                return MyThreadLocal.format("2018-04-05");
            }
        };

        ExecutorService pool = Executors.newFixedThreadPool(10);//创建一个线程池
        List<Future<Date>> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Future<Date> res = pool.submit(task);
            list.add(res);
        }
        pool.shutdown();
        System.out.println(list.size());
        for (Future<Date> f : list) {
            System.out.println(f.get());
        }
    }

    /**
     * java8 中时间格式化是不可变的，可以解决线程安全问题
     * DateTimeFormatter:用于格式化
     * LocalDate：用于操作时间，主要是给人读的时间
     */
    @Test
    public void test3() throws ExecutionException, InterruptedException {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        Callable<LocalDate> task = new Callable<LocalDate>() {
            @Override
            public LocalDate call() throws Exception {
                return LocalDate.parse("2018-04-05",dtf);
            }
        };

        ExecutorService pool = Executors.newFixedThreadPool(10);//创建一个线程池
        List<Future<LocalDate>> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Future<LocalDate> res = pool.submit(task);
            list.add(res);
        }
        pool.shutdown();
        System.out.println(list.size());
        for (Future<LocalDate> f : list) {
            System.out.println(f.get());
        }
    }

}
